package com.wisdytech.common.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.filter.CharacterEncodingFilter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * <p>ClassName: WebConfiguration</p>
 * <p>Description: web配置类</p>
 * <p>Author: zhanghailin</p>
 * <p>Date: 2018-2-7</p>
 */
@Configuration
public class WebConfiguration  {

    /**
     * 添加字符集过滤器
     * springboot配置文件中添加也可以
     * spring.http.encoding.charset=UTF-8
     * spring.http.encoding.enabled=true
     * spring.http.encoding.force=true
     * @return FilterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean () {
        // 过滤器注册
        FilterRegistrationBean  registrationBean = new FilterRegistrationBean();
        CharacterEncodingFilter encodingFilter   = new CharacterEncodingFilter();
        encodingFilter.setEncoding( StandardCharsets.UTF_8.displayName() );
        encodingFilter.setForceEncoding( true );
        // 字符过滤器
        registrationBean.setFilter( encodingFilter );
        return registrationBean;
    }

    /**
     * json null 转空
     * @param builder Jackson2ObjectMapperBuilder
     * @return ObjectMapper
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }



}
